//  this library.
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/ienum/practice/ct_enum.dart';
import 'package:hktk_app/ienum/question/question_type_enum.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/question_util.dart';
import 'package:hktk_app/util/sz_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/question/exam_count_down_widget.dart';

/// 做题测试页面标题
class QuestionTitleExamWidget extends StatefulWidget {
  /// 总题数
  final int total;

  /// 显示标题名称
  final String name;

  /// 试题页面类型
  final QuestionTypeEnum type;

  const QuestionTitleExamWidget({
    super.key,
    required this.total,
    required this.name,
    required this.type,
  });

  @override
  State<QuestionTitleExamWidget> createState() =>
      _QuestionTitleExamWidgetState();
}

class _QuestionTitleExamWidgetState extends State<QuestionTitleExamWidget> {
  late BuildContext _context;

  /// 第几题
  late int _num;

  /// 倒计时结束
  late bool _countEnd;

  late StreamSubscription<EventQuestionOnPage> _eventOnPage;

  late StreamSubscription<EventQuestionExamData> _eventExamData;

  @override
  void initState() {
    super.initState();
    debugPrint("questionTitleExamWidget 组件 -> initState 方法执行 ===> ");
    debugPrint("");
    _num = dataUtilComm.paperData!.lastIndex + 1;
    _countEnd = false;

    // 监听相应类型的事件
    _eventOnPage = eventBus.on<EventQuestionOnPage>().listen((event) {
      debugPrint(
          "questionTitleExamWidget 组件 -> 页面切换 监听执行 ===> ${event.index} : ${event.type.desc}");
      if (widget.type == event.type) {
        setState(() {
          _num = event.index + 1;
        });
      }
    });

    _eventExamData = eventBus.on<EventQuestionExamData>().listen((event) {
      debugPrint("questionTitleExamWidget 组件 -> 考试模式数据 监听执行 ===> ${event.exam}");
      if (event.exam == 1) {
        questionExamBackSaveFun(
          context: _context,
          questionType: widget.type,
          dataModel: dataUtilComm.dataModel,
          paperDataModel: dataUtilComm.paperData!,
        );
      }
    });
  }

  @override
  void dispose() {
    debugPrint("questionTitleExamWidget 组件 -> dispose 方法执行 ===> ");
    debugPrint("");
    // 页面销毁
    super.dispose();
    _eventOnPage.cancel();
    _eventExamData.cancel();
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("questionTitleExamWidget 组件 -> build 方法执行 ===> $_num");
    debugPrint("");
    _context = context;
    return Container(
      decoration: BoxDecoration(
        color: getColorWhite1(szYjms: szUtilComm.szInfo.yjms),
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(20),
          bottomRight: Radius.circular(20),
        ),
        boxShadow: [
          BoxShadow(
            color: colorBlack4,
            offset: Offset(0, 2),
            blurRadius: 8, // 阴影模糊程度
            spreadRadius: 0, // 阴影扩散程度
          )
        ],
      ),
      child: Column(
        children: [
          _titleItem(),
          _tipsItem(),
        ],
      ),
    );
  }

  /// 标题显示
  _titleItem() {
    return SizedBox(
      height: 88,
      child: Stack(
        fit: StackFit.expand,
        children: [
          _countItem(),
          _iconItem(),
        ],
      ),
    );
  }

  /// 倒计时组件
  _countItem() {
    Widget wi;
    if (widget.type == QuestionTypeEnum.exam) {
      // 考试模式
      CtEnum rType = dataUtilComm.paperData!.rType;
      if (rType == CtEnum.paperRecordRandomFormPaper) {
        // 随机组卷模式
        wi = Container();
      } else {
        // 考试模式
        wi = _countDownItem();
      }
    } else {
      wi = Container();
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        wi,
      ],
    );
  }

  /// 倒计时显示
  Widget _countDownItem() {
    if (_countEnd) {
      return Text(
        "考试结束",
        style: FontUtil.fontBlack1(28),
      );
    } else {
      int minute = dataUtilComm.paperData!.examTime;
      return ExamCountDownWidget(
        duration: Duration(minutes: minute),
        endFun: _countEndFun,
      );
    }
  }

  /// 倒计时结束方法
  _countEndFun() {
    debugPrint("questionTitleExamWidget 组件 -> 倒计时结束 ===> ");
    setState(() {
      _countEnd = true;
    });
  }

  /// 显示对应的图标数组
  _iconItem() {
    return Padding(
      padding: EdgeInsets.only(right: 30),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          _iconShowItem(
            svgUrl: "images/back/back.svg",
            size: 48,
            onTapFun: _onTapFunTc,
          ),
        ],
      ),
    );
  }

  /// 图标具体显示
  _iconShowItem({
    required String svgUrl,
    required double size,
    required Function() onTapFun,
  }) {
    return GestureDetector(
      onTap: onTapFun,
      child: SvgPicture.asset(
        svgUrl,
        width: size,
        height: size,
        color: szUtilComm.szInfo.yjms ? colorWhite1 : null,
      ),
    );
  }

  /// 显示提示组件
  _tipsItem() {
    return Container(
      height: 70,
      padding: EdgeInsets.symmetric(horizontal: 30),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
            child: Text(
              widget.name,
              style: FontUtil.fontGrey1(20),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          Text.rich(TextSpan(
            children: [
              TextSpan(
                  text: _num.toString(),
                  style: FontUtil.fontGrey2(22, fontWeight: FontWeight.w500)),
              TextSpan(
                text: "/${widget.total}",
                style: FontUtil.fontGrey1(20),
              ),
            ],
          )),
        ],
      ),
    );
  }

  /// 退出按钮点击方法
  void _onTapFunTc() {
    debugPrint("questionTitleExamWidget 组件 -> 你点击了退出按钮 ===> ");
    questionExamBackFun(
      context: _context,
      questionType: widget.type,
      questionIndex: _num - 1,
      dataModel: dataUtilComm.dataModel,
      paperDataModel: dataUtilComm.paperData!,
    );
  }
}
